using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Sockets;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.Threading;
using Gtk;
using Socket = System.Net.Sockets.Socket;

public partial class MainWindow: Gtk.Window
{	
	List<System.Net.Sockets.Socket> _list = new List<System.Net.Sockets.Socket>();
    List<ServiceHost> _hosts = new List<ServiceHost>();
	static object obj = new object();
	int writeCount = 4 * 1024;
	int readCount = 256;
	
	public bool ProcessFlag {get; set;}
	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		
		//ProcessFlag = true;
		// 启动web服务
		StartService();
	}
	
	protected void CreateService(Type _type)
	{
		ServiceHost host = new ServiceHost(_type);
		host.Opened += delegate
		{
			OutputMessage(string.Format("{0}已经启动....", _type.ToString ()));
			//Console.WriteLine("operationservice已经启动，按任意键终止服务！");
		};
		host.Closed += delegate {
			OutputMessage("服务已关闭。");
		};

		host.Open();
	}
	
	/// <summary>
    /// 批量启动服务
    /// </summary>
    public void StartService()
    {
        try
        {
            Configuration myConfiguration = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
            ServiceModelSectionGroup myServiceModelSectionGroup = (ServiceModelSectionGroup)myConfiguration.GetSectionGroup("system.serviceModel");
            OutputMessage("开始启动服务。。。");
            string AssemblyStr = ", Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";      

            foreach (ServiceElement element in myServiceModelSectionGroup.Services.Services)
            {
                System.Type mytype = System.Type.GetType(element.Name + ","+ element.Name.Split('.')[0] + AssemblyStr, true, true);
                if (mytype == null)
                {
                     throw new Exception("没发现服务：" + element.Name);
                }
				
                ServiceHost host = new ServiceHost(mytype);
                host.Open();
                _hosts.Add(host);
            }
            OutputMessage("服务已经启动");
        }
        catch (Exception)
        {
            throw;
        } 
     }

    /// <summary>
    /// 批量关闭服务
    /// </summary>
    public void CloseService()
    {
        foreach (ServiceHost host in _hosts)
        {
            host.Close();
        }
    }
	
	#region tcp old
		
	protected void OldStartService()
	{
//		TcpServer ts = new TcpServer(8080);		
//		ts.Accept += delegate(object sender, System.Net.Sockets.Socket sock) 
//		{
//			try
//			{
//				sock.ReceiveTimeout = 10000;
//				if(!sock.Connected)
//				{
//					return;
//				}
//				
//				byte[] bs = new byte[readCount];
//				NetworkStream _stream = new NetworkStream(sock);
//				_stream.Read(bs, 0, readCount);
//				string strCommand = System.Text.Encoding.Default.GetString(bs);
//				//todo:获取命令结果
//				//byte[] bResult = new byte[1024];
//				byte[] bResult = LoadResult(strCommand);
//				sock.Send(bResult);
//				_stream.Close ();
//				OutputMessage(sock.RemoteEndPoint.ToString ());
//				//_list.Add(sock);
//			}
//			catch (Exception ex)
//			{ 
//				OutputMessage(ex.ToString());
//			}
//			finally
//			{
//				sock.Close();
//			}
//		};
//		ts.Start();
		
		//ProcessRequest();
		

	}
	
	protected byte[] LoadResult (string strCommand)
	{
		switch(strCommand)
		{
			case "w":
			return System.Text.Encoding.UTF8.GetBytes("<?xml />");
			default:
			return System.Text.Encoding.UTF8.GetBytes(string.Empty);
		}
	}
	
	protected void OutputMessage(string message)
	{
		lock(obj)
		{
			if(this.textview1.Buffer.Text.Length > 5000)
			{
				this.textview1.Buffer.Text = string.Empty;
			}
			message += "\r\n";
			this.textview1.Buffer.Text += message;
		}
	}
	
	protected void ProcessRequest()
	{
		while(ProcessFlag)
		{
			foreach(System.Net.Sockets.Socket item in _list)
			{
				ThreadPool.QueueUserWorkItem(SendQueryResult, item);
			}
		}
	}
	
	protected void SendQueryResult(System.Object state)
	{
		Socket s = state as Socket;
		if(!s.Connected)
		{
			_list.Remove(s);
			return;
		}
		
		NetworkStream _stream = new NetworkStream(s);
		if(!_stream.CanRead || !_stream.DataAvailable)
		{
			return;
		}
		
		byte[] bs = new byte[256];
		_stream.Read(bs, 0, 256);
		string strCommand = System.Text.Encoding.Default.GetString(bs);
		//todo:获取命令结果
		//byte[] bResult = new byte[1024];
		byte[] bResult = System.Text.Encoding.Default.GetBytes("结果.");
		s.Send(bResult);
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
	#endregion

}
